<template>
  <div>
    <div v-show="isMove" class="screen" :style="{ zIndex: zIndex }" />
    <transition name="el-fade-in-linear">
      <div
        :id="'drag' + pIndex"
        class="dragsize"
        :style="{
          zIndex: zIndex,
          ...zStyle,
          display: isMinimized ? 'none' : 'block',
        }"
        @mousedown="selectItem"
      >
        <div class="title">
          <div class="window-controls">
            <div
              class="control-button close"
              @click.stop="closeFunc"
              title="关闭"
            ></div>
            <div
              class="control-button minimize"
              @click.stop="minimizeFunc"
              title="最小化"
            ></div>
            <div
              class="control-button maximize"
              @click.stop="fullFunc"
              title="最大化"
            ></div>
          </div>

          <div class="title-content">
            <div class="title-icon">
              <svg
                viewBox="0 0 24 24"
                width="16"
                height="16"
                stroke="currentColor"
                stroke-width="2"
                fill="none"
              >
                <rect x="2" y="4" width="20" height="16" rx="2" ry="2"></rect>
                <line x1="6" y1="12" x2="18" y2="12"></line>
              </svg>
            </div>
            <div class="title-name">
              <h2>{{ kvm.name || '终端' }}</h2>
            </div>
          </div>

          <div class="window-actions">
            <div
              class="window-action"
              :class="{ active: isFullScreen }"
              @click.stop="fullFunc"
              v-if="!isFullScreen"
              title="最大化"
            >
              <svg
                viewBox="0 0 24 24"
                width="14"
                height="14"
                stroke="currentColor"
                stroke-width="2"
                fill="none"
              >
                <rect x="3" y="3" width="18" height="18" rx="2"></rect>
                <path d="M3 9h18"></path>
              </svg>
            </div>
            <div
              class="window-action"
              @click.stop="smallFunc"
              v-else
              title="还原"
            >
              <svg
                viewBox="0 0 24 24"
                width="14"
                height="14"
                stroke="currentColor"
                stroke-width="2"
                fill="none"
              >
                <rect x="3" y="3" width="18" height="18" rx="2"></rect>
                <path d="M9 9h6v6H9z"></path>
              </svg>
            </div>
            <div
              class="window-action close-action"
              @click.stop="closeFunc"
              title="关闭"
            >
              <svg
                viewBox="0 0 24 24"
                width="18"
                height="18"
                stroke="currentColor"
                stroke-width="2.5"
                fill="none"
              >
                <line x1="18" y1="6" x2="6" y2="18"></line>
                <line x1="6" y1="6" x2="18" y2="18"></line>
              </svg>
            </div>
          </div>
        </div>
        <div class="resizeL" />
        <div class="resizeT" />
        <div class="resizeR" />
        <div class="resizeB" />
        <div class="resizeLT" />
        <div class="resizeTR" />
        <div class="resizeBR">
          <i class="iconfont icon-resize-bottom-right" />
        </div>
        <div class="resizeLB" />
        <div class="content-drag">
          <slot>暂无内容</slot>
        </div>
        <div v-if="isMove" class="content-modal" />
      </div>
    </transition>

    <!-- 最小化状态栏 -->
    <div
      v-if="isMinimized"
      class="minimized-bar"
      :style="{
        zIndex: zIndex,
        right: minimizedIndex * 210 + 'px',
      }"
      @click="restoreFromMinimized"
    >
      <div class="minimized-icon">
        <svg
          viewBox="0 0 24 24"
          width="16"
          height="16"
          stroke="currentColor"
          stroke-width="2"
          fill="none"
        >
          <rect x="2" y="4" width="20" height="16" rx="2" ry="2"></rect>
          <line x1="6" y1="12" x2="18" y2="12"></line>
        </svg>
      </div>
      <div class="minimized-title">{{ kvm.name || '终端' }}</div>
      <div class="minimized-actions">
        <div class="minimized-action" @click.stop="closeFunc" title="关闭">
          <svg
            viewBox="0 0 24 24"
            width="12"
            height="12"
            stroke="currentColor"
            stroke-width="2"
            fill="none"
          >
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* -------------------------- +
 获取id, class, tagName
 +-------------------------- */
const get = {
  byClass: (sClass, targetEle) => {
    const aClass = [];
    const reClass = new RegExp('(^| )' + sClass + '( |$)');
    const aElem = get.byTagName('*', targetEle);
    for (let i = 0; i < aElem.length; i++) {
      reClass.test(aElem[i].className) && aClass.push(aElem[i]);
    }
    return aClass;
  },
  byTagName: (elem, obj) => {
    return (obj || document).getElementsByTagName(elem);
  },
};
export default {
  props: {
    kvm: {
      type: Object,
      default: () => {
        return {};
      },
    },
    dragMinHeight: {
      type: Number,
      default: 500,
    },
    dragMinWidth: {
      type: Number,
      default: 500,
    },
    pIndex: {
      type: String,
      default: '-1',
    },
    zIndex: {
      type: Number,
      default: 0,
    },
    zStyle: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      isFullScreen: false,
      isMove: false,
      isMinimized: false,
      minimizedIndex: -1,
      originalPosition: null,
    };
  },
  mounted() {
    const oDrag = document.getElementById(`drag${this.pIndex}`);
    if (oDrag) {
      oDrag.style.width = `${this.dragMinWidth}px`;
      oDrag.style.height = `${this.dragMinHeight}px`;
    }
    this.resizeFun();
    window.addEventListener('resize', this.resizeFun);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeFun);
  },
  methods: {
    closeFunc(e) {
      e && e.stopPropagation();
      this.$emit('close', this.kvm);
    },
    minimizeFunc(e) {
      e && e.stopPropagation();
      // 保存原始位置
      const oDrag = document.getElementById(`drag${this.pIndex}`);
      if (oDrag) {
        this.originalPosition = {
          left: oDrag.style.left,
          top: oDrag.style.top,
          width: oDrag.style.width,
          height: oDrag.style.height,
        };
      }
      this.isMinimized = true;
      // 计算最小化窗口的位置
      const minimizedWindows = document.querySelectorAll('.minimized-bar');
      this.minimizedIndex = minimizedWindows.length;
      this.$emit('minimize', this.kvm);
    },
    restoreFromMinimized(e) {
      e && e.stopPropagation();
      this.isMinimized = false;
      // 恢复原始位置
      if (this.originalPosition) {
        const oDrag = document.getElementById(`drag${this.pIndex}`);
        if (oDrag) {
          Object.assign(oDrag.style, this.originalPosition);
        }
      }
      this.$emit('restore', this.kvm);
      this.selectItem();
    },
    smallFunc(e) {
      e && e.stopPropagation();
      this.isFullScreen = false;
      const oDrag = document.getElementById(`drag${this.pIndex}`);
      if (oDrag) {
        oDrag.style.width = `${this.dragMinWidth}px`;
        oDrag.style.height = `${this.dragMinHeight}px`;
        oDrag.style.left = `${
          (document.documentElement.clientWidth - oDrag.offsetWidth) / 2
        }px`;
        oDrag.style.top = `${
          (document.documentElement.clientHeight - oDrag.offsetHeight) / 2
        }px`;
      }
    },
    fullFunc(e) {
      e && e.stopPropagation();
      const oDrag = document.getElementById(`drag${this.pIndex}`);
      if (oDrag) {
        oDrag.style.top = '0';
        oDrag.style.left = '0';
        oDrag.style.width = `${document.documentElement.clientWidth - 2}px`;
        oDrag.style.height = `${document.documentElement.clientHeight - 2}px`;
        this.isFullScreen = true;
      }
    },
    selectItem() {
      this.$emit('selectItem', this.kvm);
    },
    resizeFun() {
      const oDrag = document.getElementById(`drag${this.pIndex}`);
      if (!oDrag) return;

      const oTitle = get.byClass('title', oDrag)[0];
      const oL = get.byClass('resizeL', oDrag)[0];
      const oT = get.byClass('resizeT', oDrag)[0];
      const oR = get.byClass('resizeR', oDrag)[0];
      const oB = get.byClass('resizeB', oDrag)[0];
      const oLT = get.byClass('resizeLT', oDrag)[0];
      const oTR = get.byClass('resizeTR', oDrag)[0];
      const oBR = get.byClass('resizeBR', oDrag)[0];
      const oLB = get.byClass('resizeLB', oDrag)[0];
      this.drag(oDrag, oTitle);
      // 四角
      this.resize(oDrag, oLT, true, true, false, false);
      this.resize(oDrag, oTR, false, true, false, false);
      this.resize(oDrag, oBR, false, false, false, false);
      this.resize(oDrag, oLB, true, false, false, false);
      // 四边
      this.resize(oDrag, oL, true, false, false, true);
      this.resize(oDrag, oT, false, true, true, false);
      this.resize(oDrag, oR, false, false, false, true);
      this.resize(oDrag, oB, false, false, true, false);
      if (this.isFullScreen) {
        oDrag.style.width = `${document.documentElement.clientWidth - 2}px`;
        oDrag.style.height = `${document.documentElement.clientHeight - 2}px`;
      }

      // 自定义位置
      if (Object.keys(this.zStyle).length > 0) {
        const posArr = ['left', 'top', 'right', 'bottom'];
        posArr.forEach(item => {
          if (this.zStyle[item]) {
            oDrag.style[item] = this.zStyle[item];
          } else {
            oDrag.style[item] = 'inherit';
          }
        });
      } else {
        oDrag.style.left = `${
          (document.documentElement.clientWidth - oDrag.offsetWidth) / 2
        }px`;

        oDrag.style.top = `${
          (document.documentElement.clientHeight - oDrag.offsetHeight) / 2
        }px`;
      }
    },
    drag(oDrag, targetSideEle) {
      let disX = 0;
      let dixY = 0;
      targetSideEle = targetSideEle || oDrag;
      targetSideEle.style.cursor = 'move';
      targetSideEle.onmousedown = e => {
        const event = e || window.event;
        const mouseEvent = event instanceof MouseEvent ? event : null;
        if (!mouseEvent) return;

        disX = mouseEvent.clientX - oDrag.offsetLeft;
        dixY = mouseEvent.clientY - oDrag.offsetTop;
        const dixxX = disX;
        const dixxY = dixY;
        this.isMove = true;
        document.onmousemove = e => {
          const event = e || window.event;
          const mouseEvent = event instanceof MouseEvent ? event : null;
          if (!mouseEvent) return;

          let iL = mouseEvent.clientX - dixxX;
          let iT = mouseEvent.clientY - dixxY;
          const maxL = document.documentElement.clientWidth - oDrag.offsetWidth;
          const maxT =
            document.documentElement.clientHeight - oDrag.offsetHeight;
          iL <= 0 && (iL = 0);
          iT <= 0 && (iT = 0);
          iL >= maxL && (iL = maxL);
          iT >= maxT && (iT = maxT);
          oDrag.style.left = iL + 'px';
          oDrag.style.top = iT + 'px';
          return false;
        };
        document.onmouseup = () => {
          this.isMove = false;
          document.onmousemove = null;
          document.onmouseup = null;
        };
        return false;
      };
    },
    /* -------------------------- +
      改变大小函数
      +-------------------------- */
    resize(targetEle, targetSideEle, isLeft, isTop, lockX, lockY) {
      targetSideEle.onmousedown = e => {
        const event = e || window.event;
        const mouseEvent = event instanceof MouseEvent ? event : null;
        if (!mouseEvent) return;

        const disX = mouseEvent.clientX - targetSideEle.offsetLeft;
        const disY = mouseEvent.clientY - targetSideEle.offsetTop;
        const iParentTop = targetEle.offsetTop;
        const iParentLeft = targetEle.offsetLeft;
        const iParentWidth = targetEle.offsetWidth;
        const iParentHeight = targetEle.offsetHeight;
        this.isMove = true;

        document.onmousemove = e => {
          const event = e || window.event;
          const mouseEvent = event instanceof MouseEvent ? event : null;
          if (!mouseEvent) return;

          const iL = mouseEvent.clientX - disX;
          const iT = mouseEvent.clientY - disY;
          const maxW =
            document.documentElement.clientWidth - targetEle.offsetLeft - 2;
          const maxH =
            document.documentElement.clientHeight - targetEle.offsetTop - 2;
          let iW = isLeft ? iParentWidth - iL : targetSideEle.offsetWidth + iL;
          let iH = isTop ? iParentHeight - iT : targetSideEle.offsetHeight + iT;

          if (isLeft && iL < 0) {
            targetEle.style.left = iParentLeft + iL + 'px';
          }

          if (isTop && iT < 0) {
            targetEle.style.top = iParentTop + iT + 'px';
          }

          if (iW < this.dragMinWidth) {
            iW = this.dragMinWidth;
          }

          if (iW > maxW) {
            iW = maxW;
          }

          if (!lockX) {
            targetEle.style.width = iW + 'px';
          }

          if (iH < this.dragMinHeight) {
            iH = this.dragMinHeight;
          }

          if (iH > maxH) {
            iH = maxH;
          }

          if (!lockY) {
            targetEle.style.height = iH + 'px';
          }

          return false;
        };
        document.onmouseup = () => {
          this.isMove = false;
          document.onmousemove = null;
          document.onmouseup = null;
        };
        return false;
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.icon,
.iconfont {
  margin: 0 5px;
  cursor: pointer;
  font-size: 20px;
}
.screen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.dragsize {
  position: fixed;
  top: 100px;
  left: 100px;
  width: 300px;
  height: 160px;
  background: #0c0c0c;
  border-radius: 8px;
  padding: 0;
  box-sizing: border-box;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
  border: 1px solid #222;
  overflow: hidden;
  transition: box-shadow 0.3s ease, border-color 0.3s ease;

  &:hover {
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(80, 80, 80, 0.3);
    border-color: #333;
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 42px;
    padding: 0 12px;
    background: linear-gradient(to bottom, #303030, #1c1c1c);
    border-bottom: 1px solid #333;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
    position: relative;
    cursor: move;
    user-select: none;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 1px;
      background: linear-gradient(
        to right,
        transparent,
        rgba(180, 180, 180, 0.15),
        transparent
      );
    }

    .window-controls {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 0 12px;

      .control-button {
        width: 16px;
        height: 16px;
        border-radius: 50%;
        cursor: pointer;
        transition: all 0.2s;
        position: relative;

        &::before {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%) scale(0);
          width: 24px;
          height: 24px;
          background-color: rgba(0, 0, 0, 0.1);
          border-radius: 50%;
          transition: transform 0.2s;
        }

        &.close {
          background-color: #ff5f56;

          &::before,
          &::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 8px;
            height: 1.5px;
            background-color: rgba(0, 0, 0, 0.8);
            transform-origin: center;
            opacity: 0;
            transition: opacity 0.2s ease;
          }

          &::before {
            transform: translate(-50%, -50%) rotate(45deg);
          }

          &::after {
            transform: translate(-50%, -50%) rotate(-45deg);
          }

          &:hover {
            background-color: #ff3226;
            box-shadow: 0 0 6px rgba(255, 95, 86, 0.6);

            &::before,
            &::after {
              opacity: 1;
            }
          }
        }

        &.minimize {
          background-color: #ffbd2e;

          &::before {
            width: 6px;
            height: 1px;
            background-color: rgba(0, 0, 0, 0.5);
          }

          &:hover {
            background-color: #ffae00;
            box-shadow: 0 0 6px rgba(255, 189, 46, 0.6);

            &::before {
              transform: translate(-50%, -50%) scale(1);
              opacity: 1;
            }
          }
        }

        &.maximize {
          background-color: #27c93f;

          &::before {
            width: 6px;
            height: 6px;
            border: 1px solid rgba(0, 0, 0, 0.5);
            background-color: transparent;
            border-radius: 1px;
            box-sizing: border-box;
          }

          &:hover {
            background-color: #1aad2f;
            box-shadow: 0 0 6px rgba(39, 201, 63, 0.6);

            &::before {
              transform: translate(-50%, -50%) scale(1);
              opacity: 1;
            }
          }
        }
      }
    }

    .title-content {
      display: flex;
      align-items: center;
      flex: 1;
      padding: 0 15px;
      justify-content: center;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -8px;
        left: 30%;
        right: 30%;
        height: 1px;
        background: linear-gradient(
          to right,
          transparent,
          rgba(150, 150, 150, 0.1),
          transparent
        );
        opacity: 0;
        transition: opacity 0.3s ease;
      }

      &:hover::after {
        opacity: 1;
      }

      .title-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;
        color: #aaa;
      }

      .title-name {
        text-align: center;
        max-width: 70%;

        h2 {
          margin: 0;
          font-size: 14px;
          font-weight: 600;
          color: #e0e0e0;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          letter-spacing: 0.5px;
          text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
          position: relative;
        }
      }
    }

    .window-actions {
      display: flex;
      align-items: center;
      gap: 8px;

      .window-action {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 28px;
        height: 28px;
        border-radius: 4px;
        background-color: rgba(255, 255, 255, 0.04);
        color: #e8e8e8;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          background-color: rgba(255, 255, 255, 0.08);
          color: #ccc;
        }

        &:active {
          transform: translateY(1px);
        }

        &.active {
          color: #999;
          background-color: rgba(255, 255, 255, 0.08);
        }

        &.close-action {
          background-color: rgba(255, 85, 85, 0.05);
          color: #ff5f56;
          position: relative;
          overflow: hidden;

          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(
              circle at center,
              rgba(255, 95, 86, 0.15),
              transparent 70%
            );
            opacity: 0;
            transition: opacity 0.3s ease;
          }

          &:hover {
            background-color: rgba(255, 85, 85, 0.15);
            color: #ff3226;
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(255, 85, 85, 0.2);

            &::before {
              opacity: 1;
              animation: pulse-red 2s infinite;
            }

            svg {
              animation: rotate-x 0.3s ease;
            }
          }

          &:active {
            transform: scale(0.95);
            box-shadow: 0 1px 4px rgba(255, 85, 85, 0.2);
          }
        }
      }
    }
  }

  .content-drag {
    overflow: auto;
    width: 100%;
    margin: 0;
    height: calc(100% - 42px);
    background-color: #121212;
  }

  .content-modal {
    position: absolute;
    top: 42px;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.05);
    backdrop-filter: blur(0.5px);
  }

  // 保留原有的resize相关样式
  .resizeBR {
    position: absolute;
    width: 14px;
    height: 16px;
    right: 0;
    bottom: 0;
    overflow: hidden;
    cursor: nw-resize;
    z-index: 2;
  }
  .resizeL,
  .resizeT,
  .resizeR,
  .resizeB,
  .resizeLT,
  .resizeTR,
  .resizeLB {
    position: absolute;
    overflow: hidden;
    opacity: 0;
    filter: alpha(opacity=0);
    z-index: 1;
  }
  .resizeL,
  .resizeR {
    top: 0;
    width: 5px;
    height: 100%;
    cursor: w-resize;
  }

  .resizeL {
    left: -2px;
  }

  .resizeR {
    right: 0;
  }
  .resizeT,
  .resizeB {
    width: 100%;
    height: 5px;
    cursor: n-resize;
  }
  .resizeT {
    top: 0;
  }
  .resizeB {
    bottom: 0;
  }
  .resizeLT,
  .resizeTR,
  .resizeLB {
    width: 16px;
    height: 16px;
  }
  .resizeLT {
    top: 0;
    left: 0;
    cursor: nw-resize;
  }
  .resizeTR {
    top: 0;
    right: 0;
    cursor: ne-resize;
  }
  .resizeLB {
    left: 0;
    bottom: 0;
    cursor: ne-resize;
  }
}

/* 最小化状态栏样式 */
.minimized-bar {
  position: fixed;
  bottom: 0;
  width: 200px;
  height: 40px;
  background: #1a1a1a;
  display: flex;
  align-items: center;
  padding: 0 12px;
  border: 1px solid #333;
  border-bottom: none;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 8px 8px 0 0;
  z-index: 9999; /* 确保最小化窗口始终显示在最上层 */

  &:hover {
    background: #222;
    transform: translateY(-2px);
  }

  .minimized-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #aaa;
    margin-right: 10px;
  }

  .minimized-title {
    flex: 1;
    font-size: 13px;
    font-weight: 500;
    color: #e0e0e0;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .minimized-actions {
    display: flex;
    align-items: center;

    .minimized-action {
      width: 20px;
      height: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #aaa;
      cursor: pointer;
      border-radius: 3px;

      &:hover {
        color: #ff3226;
        background-color: rgba(255, 85, 85, 0.1);
      }
    }
  }
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}

@keyframes pulse-red {
  0% {
    opacity: 0.2;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 0.2;
  }
}

@keyframes rotate-x {
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(180deg);
  }
}
</style>
